using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MouseKeyboardOperationSimulator
{
    /// <summary>
    /// 输入法帮助类，用于处理输入法切换相关功能
    /// </summary>
    public static class InputMethodHelper
    {
        // Windows API常量
        private const int WM_INPUTLANGCHANGEREQUEST = 0x0050;
        private const long KL_NAMELENGTH = 9;

        // Windows API函数声明
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetKeyboardLayout(int idThread);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);

        /// <summary>
        /// 切换到英文输入法
        /// </summary>
        public static void SwitchToEnglishInput()
        {
            try
            {
                // 获取当前前台窗口句柄
                IntPtr hwnd = GetForegroundWindow();
                
                // 美国英语键盘布局标识
                const string englishLayout = "00000409";
                
                // 加载英文键盘布局
                IntPtr hkl = LoadKeyboardLayout(englishLayout, 0x00000001); // KLF_ACTIVATE
                
                // 发送WM_INPUTLANGCHANGEREQUEST消息请求切换输入法
                PostMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, hkl);
            }
            catch (Exception ex)
            {
                // 记录异常但不中断程序执行
                MessageBox.Show($"切换输入法时发生错误: {ex.Message}", "输入法切换错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}